using UnityEngine;
using System;
using System.Collections.Generic;
using Newtonsoft.Json;

public class JiLiAd : MonoBehaviour
{
    private string adUnitId = "";
    public event Action<string, MaxSdkBase.AdInfo> OnAdCompleted;
    public event Action OnAdFailed;

    public void initRewardAd()
    {
        adUnitId = (string)Data.adsConfig["type_config"]["reward"];
        // 初始化回调
        MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedAdLoadedEvent;
        MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedAdLoadFailedEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedAdDisplayedEvent;
        MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedAdClickedEvent;
        MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedAdRevenuePaidEvent;
        MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedAdHiddenEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedAdFailedToDisplayEvent;
        MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedAdReceivedRewardEvent;

        // 加载第一个广告
        LoadRewardedAd();
    }

    private void LoadRewardedAd()
    {
        Tools.Log("激励广告", "加载中...." + adUnitId);
        MaxSdk.LoadRewardedAd(adUnitId);
    }

    public void ShowRewardedAd()
    {
        ShowRewardedAdNow();
    }

    //暴露给oc的方法
    public void ShowRewardedAdNow()
    {
        if (MaxSdk.IsRewardedAdReady(adUnitId))
        {
            MaxSdk.ShowRewardedAd(adUnitId);
        }
    }

    public bool IsRewardedAdReady()
    {
        return MaxSdk.IsRewardedAdReady(adUnitId);
    }

    private void OnRewardedAdLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
    }
    private void OnRewardedAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
    {
    }
    private void OnRewardedAdDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
    }
    private void OnRewardedAdClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
    }
    private void OnRewardedAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
    }
    private void OnRewardedAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        GlobalEventManager.EmitEvent("AdsPlaybackCompleted");
        LoadRewardedAd();
    }
    private void OnRewardedAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
    {
        LoadRewardedAd();

        OnAdFailed?.Invoke();
    }
    private void OnRewardedAdReceivedRewardEvent(string adUnitId, MaxSdkBase.Reward reward, MaxSdkBase.AdInfo adInfo)
    {
        OnAdCompleted?.Invoke(adUnitId, adInfo);
    }
}